package com.example.icedcap.topeka_fake.helper;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;

import com.example.icedcap.topeka_fake.model.Avatar;
import com.example.icedcap.topeka_fake.model.Player;

/**
 * Created by doushuqi on 15-7-11上午11:02.
 * Email:doushuqi0409@gmail.com
 */
public class PreferenceHelper {
    private static final String PREFERENCE_PLAYER = "player";
    private static final String PREFERENCE_FIRST_USERNAME = PREFERENCE_PLAYER + ".firstName";
    private static final String PREFERENCE_LAST_INITIAL = PREFERENCE_PLAYER + ".lastInitial";
    private static final String PREFERENCE_AVATAR = PREFERENCE_PLAYER + ".avatar";

    public static Player getPlayer(Context context) {
        final String firstName = getSharePreferences(context).getString(PREFERENCE_FIRST_USERNAME, null);
        final String lastInitial = getSharePreferences(context).getString(PREFERENCE_LAST_INITIAL, null);
        final String avatarNum = getSharePreferences(context).getString(PREFERENCE_AVATAR, null);
        final Avatar avatar;
        if (avatarNum != null) {
            avatar = Avatar.valueOf(avatarNum);
        }else {
            avatar = null;
        }
        if (null == firstName && null == lastInitial && null == avatar) {
            return null;
        }
        return new Player(firstName, lastInitial, avatar);
    }

    public static void writeToPreference(Context context, Player player) {
        SharedPreferences.Editor editor = getEditor(context);
        editor.putString(PREFERENCE_FIRST_USERNAME, player.getFirstName());
        editor.putString(PREFERENCE_LAST_INITIAL, player.getLastInitial());
        editor.putString(PREFERENCE_AVATAR, player.getAvatar().name());
        editor.apply();
    }

    public static void signOut(Context context) {
        SharedPreferences.Editor editor = getEditor(context);
        editor.remove(PREFERENCE_FIRST_USERNAME);
        editor.remove(PREFERENCE_LAST_INITIAL);
        editor.remove(PREFERENCE_AVATAR);
        editor.apply();
    }

    public static boolean isSignIn(Context c) {
        final SharedPreferences preferences = getSharePreferences(c);
        return preferences.contains(PREFERENCE_FIRST_USERNAME)&&
                preferences.contains(PREFERENCE_LAST_INITIAL)&&
                preferences.contains(PREFERENCE_AVATAR);
    }

    private static SharedPreferences getSharePreferences(Context context) {
        return context.getSharedPreferences(PREFERENCE_PLAYER, Context.MODE_PRIVATE);
    }

    private static SharedPreferences.Editor getEditor(Context context) {
        return getSharePreferences(context).edit();
    }
}
